﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.Text;
using System.Windows.Forms;

namespace Sl.Support.Forms {
	internal class ToolStripNumTextBox : System.Windows.Forms.ToolStripTextBox {


		public ToolStripNumTextBox() : base() {
		}
		[Category("行为"), Description("获取或设置数据修改后会直接影响Text"), Browsable(true)]
		public long Num {
			get {
				long num = 0;
				switch (Num_model) {
					case NumModel.Hexadecimal:
						long.TryParse(this.Text,NumberStyles.HexNumber, NumberFormatInfo.CurrentInfo, out num);
						break;
					case NumModel.Decimal:
						long.TryParse(this.Text, NumberStyles.Integer, NumberFormatInfo.CurrentInfo, out num);
						break;
				}
					return num;
			}

			set {
				switch (Num_model) {
					case NumModel.Hexadecimal:
						Text = value.ToString("X");
						break;
					case NumModel.Decimal:
						Text = value.ToString();
						break;
					default:
						throw new InvalidCastException("数据类型只允许 HexNumber 和 Integer");
				}
			}
		}
		[Category("行为"), Description("以十进制还是十六进制显示数据"), Browsable(true)]

		[DefaultValue(NumModel.Decimal)]
		public NumModel Num_model { get; set; } = NumModel.Decimal;
		protected override void OnKeyPress(KeyPressEventArgs e) {
			if ((e.KeyChar == '+') || (e.KeyChar == '-')) {
				base.OnKeyPress(e);
				return ;
			} else
			if (e.KeyChar >= '0' && e.KeyChar <= '9') {
				base.OnKeyPress(e);
				return;
			} else
			if ((e.KeyChar >= 'a' && e.KeyChar <= 'f') || (e.KeyChar >= 'A' && e.KeyChar <= 'F')) {
				if (Num_model == NumModel.Hexadecimal) {
					base.OnKeyPress(e);
					return;
				}
			} else
			if ((e.KeyChar == Convert.ToChar(Keys.Back))|| (e.KeyChar == Convert.ToChar(Keys.Delete)) ) {
				base.OnKeyPress(e);
				return;
			} else
			if (e.KeyChar == Convert.ToChar(Keys.Enter)) {
				onInputEnter();
				return;
			}

			onInputBadKey(e);
			e.Handled = true;
			return;
		}


		event EventHandler<KeyPressEventArgs> eInputBadKey;
		virtual protected void onInputBadKey(KeyPressEventArgs e) {
			eInputBadKey?.Invoke(this, e);
		}

		event EventHandler eInputEnter;
		virtual protected void onInputEnter() {
			eInputEnter?.Invoke(this, EventArgs.Empty);
		}
	}

	enum NumModel {
		Hexadecimal, Decimal,

	}
}
